package com.loong.mapper.impl;

import com.loong.mapper.CartMapper;
import com.loong.pojo.Cart;
import com.loong.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

public class CartMapperImpl implements CartMapper {
    Logger logger = Logger.getLogger(CartMapperImpl.class);

    @Override
    public void updateCart(Cart cart) {
        try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
            CartMapper mapper = sqlSession.getMapper(CartMapper.class);
            mapper.updateCart(cart);
            sqlSession.commit();
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    @Override
    public void insertCart(Cart cart) {
        try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
            CartMapper mapper = sqlSession.getMapper(CartMapper.class);
            mapper.insertCart(cart);
            sqlSession.commit();
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    @Override
    public List<Cart> selectCartsByUid(Integer uid) {
        try (SqlSession sqlSession = MybatisUtils.getSqlSession()) {
            CartMapper mapper = sqlSession.getMapper(CartMapper.class);
            return mapper.selectCartsByUid(uid);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public Cart hasCart(int uid, int pid) {
        try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
            CartMapper mapper = sqlSession.getMapper(CartMapper.class);
            return mapper.hasCart(uid, pid);
        }catch (Exception e){
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public void deleteCartByCid(String cid) {
        try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
            CartMapper mapper = sqlSession.getMapper(CartMapper.class);
           mapper.deleteCartByCid(cid);
            sqlSession.commit();
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    @Override
    public void updateCartByCid(BigDecimal cprice, int cnum, String cid) {
        try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
            CartMapper mapper = sqlSession.getMapper(CartMapper.class);
            mapper.updateCartByCid(cprice, cnum, cid);
            sqlSession.commit();
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    @Override
    public void deleteCartByUid(int uid) {
        try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
            CartMapper mapper = sqlSession.getMapper(CartMapper.class);
            mapper.deleteCartByUid(uid);
            sqlSession.commit();
        }
    }
}
